package com.ang.juc.n3;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class InterruptTest {
    public static void main(String[] args) throws Exception {

        test2();
    }


    /**
     * 正在运行的线程，调用interrupt后，不会影响线程的正常运行
     * 但是打断状态会改变
     */
    public static void test1(){
        Thread t = new Thread(()->{
            while (true){
                if(Thread.currentThread().isInterrupted()){
                    log.info("线程被打断，打断状态：{}",Thread.currentThread().isInterrupted());
                    //调用interrupt后，不会影响正常运行
                    break;
                }
                log.info("线程正在运行");
            }
        });

        t.start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        //2s后打断
        t.interrupt();
    }

    /**
     * interrupt可以打断wait、sleep和join中，阻塞状态下的线程
     * 阻塞的线程，打断后会抛异常
     * 抛出异常后，会将线程的打断状态清空，从true变为false
     */
    public static void test2() throws Exception{
        Thread t = new Thread(()->{
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });


        t.start();

        Thread.sleep(2000);
        //2s后打断
        t.interrupt();
        Thread.sleep(1000);
        //1s后等出现异常后再打印状态，因为异常后会将状态改为false
        log.info("打断状态：{}",t.isInterrupted());
    }

    public static void test3(){

    }
}
